<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\Reception;
use App\Enums\ReceptionType;
use App\Enums\UserStatus;
use App\Models\User;
use App\Services\ReceptionService;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class ReceptionController extends AdminController
{
    protected int $type;

    protected $title = '';

    public bool $show_column_selector = false;


    public function __construct(Request $request)
    {
        $this->type = $request->get('type', ReceptionType::SALE);
        $this->title = ReceptionType::getDescription($this->type) . '接待';
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid(): Grid
    {
        return Grid::make(new Reception(), function (Grid $grid) {
            $edit = Admin::user()->can($this->edit_permission_name);
            $grid->model()
                ->with(['user'])
                ->where('type', $this->type)
                ->orderByDesc('id');
            $grid->column('user.name', trans('reception.fields.user_id'));
            $grid->column('today_number');
            if ($edit) {
                $grid->column('daily_number')->editable(true);
                $grid->column('weight')->editable(true);
                $grid->column('status')->switch();
            } else {
                $grid->column('daily_number');
                $grid->column('weight');
                $grid->column('status')->bool();
            }
            $grid->column('created_at');

            $grid->filter(function (Grid\Filter $filter) {
                $filter->like('user.name', trans('reception.fields.user_id'));
                $filter->equal('status')->select(getBoolOption());
            });


            //新增按钮追加参数
            $grid->model()->setConstraints([
                'type' => $this->type,
            ]);
            $this->gridCommon($grid);
            $grid->enableDialogCreate();
            $grid->showQuickEditButton();

            $grid->header(function () use ($grid) {
                $str = '';
                $service = new ReceptionService($this->type);
                $reception = $service->getReceptionUserList($service->reception_user_cache_key);
                $str .= "接待人员：$reception <br>";
                return "<div style='padding: 10px;'>" . $str . '</div><br>';
            });
        });
    }


    /**
     * Make a form builder.
     *
     * @return Form
     */
//    protected function form(): Form
//    {
//        return Form::make(new Reception(), function (Form $form) {
//            if ($form->isCreating()) {
//                $form->hidden('type')->default(request('type', ReceptionType::SALE));
//                $form->select('admin_user_id')->required()
//                    ->options(config('admin.database.users_model')::query()->whereHas('roles', function ($query) {
//                        $query->where('slug', Str::lower(Str::replace('_', '-', ReceptionType::getKey((int)request('type', ReceptionType::SALE)))));
//                    })->pluck('name', 'id'));
//            } else {
//                $form->hidden('type');
//                $form->text('user_name', trans('reception.fields.admin_user_id'))
//                    ->default($form->model()->admin_user_id ? config('admin.database.users_model')::query()->where('id', $form->model()->admin_user_id)->value('name') : '', true)
//                    ->readOnly();
//            }
//            $form->number('daily_number')->min(0)->max(100);
//            $form->number('weight')->default(1)->min(1)->max(20);
//            $form->switch('status')->default(true);
//
//
//            $form->saving(function (Form $form) {
//                if ($form->isCreating()) {
//                    if (\App\Models\Reception::query()->where('admin_user_id', $form->input('admin_user_id'))->exists()) {
//                        return $form->response()->error('员工已存在');
//                    }
//                }
//            });
//            $form->ignore(['user_name']);
//        });
//    }

    protected function form(): Form
    {
        return Form::make(new Reception(), function (Form $form) {
            $form->display('id');
            if ($form->isCreating()) {
                $form->hidden('type')->default(request('type', ReceptionType::SALE));
                $form->select('user_id')
                    ->required()
                    ->options(
                        User::query()
                            ->where('status', UserStatus::WORKING)
                            ->whereNotIn('id', \App\Models\Reception::query()->pluck('user_id'))
                            ->whereHas('adminUser.roles', function ($query) {
                                $sale = Str::lower(Str::replace('_', '-', ReceptionType::getKey((int)request('type', ReceptionType::SALE))));
                                $query->whereIn('slug', [$sale, $sale . '-manage']);
                            })
                            ->pluck('name', 'id'));
            } else {
                $form->hidden('type');
                $form->text('user_name', trans('reception.fields.user_id'))
                    ->default($form->model()->user_id ? User::query()->where('id', $form->model()->user_id)->value('name') : '', true)
                    ->readOnly();
            }
            $form->number('daily_number')->min(0)->max(100);
            $form->number('weight')->default(1)->min(1)->max(20);
            $form->switch('status')->default(true);


            $form->saving(function (Form $form) {
                if ($form->isCreating()) {
                    if (\App\Models\Reception::query()->where('user_id', $form->input('user_id'))->exists()) {
                        return $form->response()->error('员工已存在');
                    }
                }
                if ($form->isEditing()) {
                    //编辑的时候判断员工状态是否正常
                    if ($form->input('status') && User::query()->where('id', $form->model()->user_id)->value('status') == UserStatus::DEPART) {
                        return $form->response()->error('员工已离职，不可开启接待')->refresh();
                    }
                }
            });
            $form->ignore(['user_name']);
        });
    }
}
